// 特征值管理
'use strict';

const newFaceFeatureModel = require('../models/new_face_feature.model');
const userModel = require('../models/user.model');
const mongoose = require('mongoose');
const Code = require('../common/error_code');
const Cons = require('../common/constants');
const httpUtil = require('../utils/http');
const globalConfig = require('../../config/global_config');

async function list(ctx) {
    // 校验参数
    const params = ctx.request.body;
    const result = await newFaceFeatureModel.find({group_id:params.group_id||"-1"})
    return ctx.success(Code.REQUEST_SUCCESS('请求成功'), result)
}

async function save(ctx){
    try{
        const params = ctx.request.body
        if(!params.id){
            return ctx.error(Code.REQUEST_ERROR('缺少学生信息'))
        }
        const student = await userModel.findOne({_id:params.id,u_tp:Cons.USER_TYPE_STUDENT})
        if(!student){
            return ctx.error(Code.REQUEST_ERROR('未找到该学生'))
        }
        if(!student.u_hp){
            return ctx.error(Code.REQUEST_ERROR('该学生没有设置头像'))
        }
        let operate_cmd = 1, faceId, isAdd = true;
        if(student.feature_id){
            isAdd = false
            faceId = student.feature_id
        }else{
            faceId = new mongoose.Types.ObjectId()
        }
        // const feature = await newFaceFeatureModel.findById(faceId)   
        const req = {
            operate_cmd,
            group_id: params.group_id||"-1",
            feature_id: faceId,
            FaceId:-1,
            FacePicture: student.u_hp
        }
        const resData = await httpUtil.postWithTimeout(`${globalConfig.faceRecognitionServer}/facerec-ipc`,req)
        const res = resData&&resData.data;
        if(res.face_feature) {
            await userModel.updateOne({_id:params.id},{feature_id:faceId})
            if(isAdd){
                await newFaceFeatureModel.create({
                    _id: faceId,
                    group_id: res.group_id,
                    features: res.face_feature||[],
                    // u_tp:5
                    // person_id: student._id,
                })
            }else{
                await newFaceFeatureModel.updateOne({_id:faceId},{
                    group_id: res.group_id,
                    features: res.face_feature||[],
                    // u_tp:5
                    // person_id: student._id,
                })
            }
            ctx.success(Code.REQUEST_SUCCESS('保存成功'))
        }else{
            ctx.error(Code.REQUEST_ERROR('保存失败'))
        }
    }catch(err){
        ctx.error(Code.REQUEST_ERROR('操作失败'))
    }
}

async function del(ctx){
    try{
        const params = ctx.request.body
        if(!params.id){
            return ctx.error(Code.REQUEST_ERROR('缺少学生信息'))
        }
        const student = await userModel.findOneAndUpdate({_id:params.id,u_tp:Cons.USER_TYPE_STUDENT},{feature_id:''})
        if(!student){
            return ctx.error(Code.REQUEST_ERROR('未找到该学生'))
        }
        await newFaceFeatureModel.deleteOne({_id:student.feature_id})
        return ctx.success(Code.REQUEST_SUCCESS('删除成功'))
    }catch(err){
        ctx.error(Code.REQUEST_ERROR('删除失败'))
    }
}


async function batchSave(ctx){
    try{
        const params = ctx.request.body
        if(!params.ids||!Array.isArray(params.ids)){
            return ctx.error(Code.REQUEST_ERROR('缺少学生信息'))
        }
        const ids = params.ids
        let errorMsgAry = []
        for(let id of ids){
            const student = await userModel.findOne({_id:id,u_tp:Cons.USER_TYPE_STUDENT})
            if(!student){    
                continue
            }  
            if(!student.u_hp){
                errorMsgAry.push(`${student.u_nm}(${student.s_num})头像为空`)
                continue
            }
            let operate_cmd = 1, faceId, isAdd = true;
            if(student.feature_id){
                isAdd = false
                faceId = student.feature_id
            }else{
                faceId = new mongoose.Types.ObjectId()
            }
            try{
                const req = {
                    operate_cmd,
                    group_id: params.group_id||"-1",
                    feature_id: faceId,
                    FaceId:-1,
                    FacePicture: student.u_hp
                }
                const resData = await httpUtil.postWithTimeout(`${globalConfig.faceRecognitionServer}/facerec-ipc`,req)
                const res = resData&&resData.data;
                if(res.face_feature) {
                    await userModel.updateOne({_id:id},{feature_id:faceId})
                    if(isAdd){
                        await newFaceFeatureModel.create({
                            _id: faceId,
                            group_id: res.group_id,
                            features: res.face_feature||[],
                            // u_tp:5
                            // person_id: student._id,
                        })
                    }else{
                        await newFaceFeatureModel.updateOne({_id:faceId},{
                            group_id: res.group_id,
                            features: res.face_feature||[],
                            // u_tp:5
                            // person_id: student._id,
                        })
                    }
                    // ctx.success(Code.REQUEST_SUCCESS('保存成功'))
                }else{
                    errorMsgAry.push(`${student.u_nm}(${student.s_num})保存失败`)
                    // return ctx.error(Code.REQUEST_ERROR('保存失败'))
                }
            }catch(err){
                errorMsgAry.push(`${student.u_nm}(${student.s_num})保存失败`)
                // return ctx.error(Code.REQUEST_ERROR('操作失败'))
            }
        }
        if(errorMsgAry.length){
            return ctx.error(Code.REQUEST_ERROR_MODAL(errorMsgAry.join(';')))
        }
        return ctx.success(Code.REQUEST_SUCCESS('保存成功'))
    }catch(err){
        ctx.error(Code.REQUEST_ERROR('操作失败'))
    }
}
exports.list = list
exports.save = save
exports.delete = del
exports.batch_save = batchSave